package code.sbxj.qwd.com.sbxj;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.CacheDiskUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.UnsupportedEncodingException;


@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {

    @ViewInject(R.id.listview)
    private ListView listview;

    @ViewInject(R.id.titleright)
    private TextView titleright;

    @ViewInject(R.id.titleleft)
    private TextView titleleft;

    MyAdapter myadapter;
    JSONArray dataArray = new JSONArray();

    boolean isoffline;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        NfcUtils nfcUtils = new NfcUtils(this);


        initView();

        CacheDiskUtils.getInstance().put("isoffline", true);
        isoffline = (boolean) CacheDiskUtils.getInstance().getSerializable("isoffline", false);

        titleright.setVisibility(View.VISIBLE);
        titleright.setText("上传");
        titleright.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, UploadListActivity.class);
                startActivity(intent);
            }
        });
        titleleft.setVisibility(View.VISIBLE);
        titleleft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                AlertDialog.Builder normalDialog =
                        new AlertDialog.Builder(MainActivity.this);
                normalDialog.setTitle("温馨提示");
                normalDialog.setMessage("是否退出当前账户？");
                normalDialog.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                CookieSyncManager.createInstance(MainActivity.this);
                                CookieManager.getInstance().removeAllCookie();
                                finish();
                            }
                        });
                normalDialog.setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        });
                // 显示
                normalDialog.show();
            }
        });
        findViewById(R.id.back).setVisibility(View.GONE);
        getUserInfo();
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        //开启前台调度系统
//        NfcUtils.mNfcAdapter.enableForegroundDispatch(this, NfcUtils.mPendingIntent, NfcUtils.mIntentFilter, NfcUtils.mTechList);
//
//    }
//
//    @Override
//    protected void onPause() {
//        super.onPause();
//        //关闭前台调度系统
//        NfcUtils.mNfcAdapter.disableForegroundDispatch(this);
//    }
//
//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        //当该Activity接收到NFC标签时，运行该方法
//        //调用工具方法，读取NFC数据
//        try {
//            String str = NfcUtils.readNFCFromTag(intent);
//            Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//    }
    int i=0;
    void initView() {


        findViewById(R.id.titletv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                i=i+1;
                if(i>=15){
                    CheckLineActivity.islock=false;
                }
            }
        });



        myadapter = new MyAdapter();
        listview.setAdapter(myadapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                if (isoffline) {
                    try {
                        int taskid = dataArray.getJSONObject(i).optInt("id");
                        if (CacheDiskUtils.getInstance().getJSONObject("offlinedata" + taskid) != null) {
                                CacheDiskUtils.getInstance().put("offlinedata", CacheDiskUtils.getInstance().getJSONObject("offlinedata" + taskid));
                            Intent intent = new Intent();
                            CacheDiskUtils.getInstance().put("task_id",taskid);
                            intent.setClass(MainActivity.this, CheckLineActivity.class);
                            intent.putExtra("linename", dataArray.getJSONObject(i).optString("lineName"));
                            intent.putExtra("lineid", taskid);
                            startActivity(intent);
                            return;
                        }


                        downLoadData(dataArray.getJSONObject(i).optInt("id"), dataArray.getJSONObject(i).optString("lineName"),false);
                        return;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                Intent intent = new Intent();
                intent.setClass(MainActivity.this, CheckLineActivity.class);
                try {
                    intent.putExtra("linename", dataArray.getJSONObject(i).optString("lineName"));
                    intent.putExtra("lineid", dataArray.getJSONObject(i).optInt("lineId"));
                    startActivity(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    class MyAdapter extends BaseAdapter {
        private LayoutInflater mInflater;


        //返回数据集的长度
        @Override
        public int getCount() {
            return dataArray.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return dataArray.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        //这个方法才是重点，我们要为它编写一个ViewHolder
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            convertView = getLayoutInflater().inflate(R.layout.activity_taskiterm, null);

            TextView linename = convertView.findViewById(R.id.linename);
            TextView deptname = convertView.findViewById(R.id.deptname);
            TextView download = convertView.findViewById(R.id.download);

            final int index = position;
            me.zhouzhuo.zzhorizontalprogressbar.ZzHorizontalProgressBar progressbar = convertView.findViewById(R.id.pb);
            try {
                linename.setText(position+1 + "  " + dataArray.getJSONObject(position).optString("lineName"));
                deptname.setText(dataArray.getJSONObject(position).optString("deptName"));
                int totlecount = dataArray.getJSONObject(position).optInt("total");
                int finishcount = dataArray.getJSONObject(position).optInt("finishCount");
                if (totlecount > 0) {
                    progressbar.setProgress(finishcount * 100 / totlecount);
                } else {
                    progressbar.setProgress(0);
                }

                download.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            downLoadData(dataArray.getJSONObject(index).optInt("id"), dataArray.getJSONObject(index).optString("lineName"), false);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return convertView;
        }


    }

    private void getUserInfo() {
        if(CacheDiskUtils.getInstance().getString("cookie")==null){
            JSONObject obj  = CacheDiskUtils.getInstance().getJSONObject("userinfo");
            if(obj!=null){
                setTitleText("欢迎：" + obj.optString("deptName") + "--" + obj.optString("name"));
                getTasklist(obj.optInt("deptId"));
                CacheDiskUtils.getInstance().put("userid", obj.optInt("deptId") + "");
            }
            return;
        }


        ShowLoading();
        RequestParams params = new RequestParams(Config.BaseUrl + "mgr/currentInfo");
        params.setUseCookie(true);
        params.addHeader("cookie", CacheDiskUtils.getInstance().getString("cookie"));
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                Log.e("result", result);

                try {
                    JSONObject obj = new JSONObject(result);
                    setTitleText("欢迎：" + obj.optString("deptName") + "--" + obj.optString("name"));
                    getTasklist(obj.optInt("deptId"));
                    CacheDiskUtils.getInstance().put("userid", obj.optInt("deptId") + "");
                    CacheDiskUtils.getInstance().put("userinfo", obj);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void getTasklist(int deptId) {

        if(CacheDiskUtils.getInstance().getString("cookie")==null){
            dataArray = CacheDiskUtils.getInstance().getJSONArray("taskdata");
            if(dataArray!=null){
                myadapter.notifyDataSetChanged();
            }
            return;
        }

//        ShowLoading();
        RequestParams params = new RequestParams(Config.BaseUrl + "task/processingList?deptId=" + deptId);
        params.setUseCookie(true);
        params.addHeader("cookie", CacheDiskUtils.getInstance().getString("cookie"));
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                Log.e("result", result);

                try {
                    dataArray = new JSONArray(result);
                    CacheDiskUtils.getInstance().put("taskdata", dataArray);
                    myadapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                CancleLoading();
            }
        });
    }


    private void downLoadData(final int taskid, final String taskname, final boolean isneedOpen) {
        ShowLoading();
        RequestParams params = new RequestParams(Config.BaseUrl + "task/download?taskId=" + taskid);
        params.setUseCookie(true);
        params.addHeader("cookie", CacheDiskUtils.getInstance().getString("cookie"));
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                if (!isneedOpen) {
                    try {
                        CacheDiskUtils.getInstance().put("offlinedata" + taskid, new JSONObject(result).getJSONObject("line"));
                        Toast.makeText(x.app(), "下载成功!", Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    return;
                }

                Log.d("result_down", result);
                try {
                    CacheDiskUtils.getInstance().put("offlinedata" + taskid, new JSONObject(result).getJSONObject("line"));
                    CacheDiskUtils.getInstance().put("offlinedata", CacheDiskUtils.getInstance().getJSONObject("offlinedata" + taskid));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, CheckLineActivity.class);
                intent.putExtra("linename", taskname);
                intent.putExtra("lineid", taskid);
                startActivity(intent);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                CancleLoading();
            }
        });
    }

    private long mExitTime;

    //对返回键进行监听
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            exit();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast.makeText(MainActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
            mExitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }
    }

}
